<?php

/*
*/

class Stock_Detail_model extends CI_Model
{

	static $TABLE;
	public $error;

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		$this->load->database($this->test_database->get_db());
		//载入模型
		$this->load->model('Inbound_Type_model');
		$this->load->model('Outbound_Type_model');
		//载入库文件
		$this->load->library('form_validation');
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//初始化
		$this->TABLE = 'stocks_details';
		$this->error = false;
	}

	public function create($stock_id, $store_type, $stock_type, $bound_type_id, $sub_goods_ids, $quantities, $supplier_ids=array(), $prices=array())
	{

		$this->load->model('Sub_goods_model');

		$data = array();
		$data['stock_id'] = $stock_id;
		$data['stock_type'] = $stock_type;
		$data['bound_type_id'] = $bound_type_id;
		$data['create_date'] = time();
		foreach ($sub_goods_ids as $k=>$v)
		{
			$data['sub_goods_id'] = $sub_goods_ids[$k];
			$data['quantity'] = $quantities[$k];
			if (!empty($supplier_ids))
			{
				$data['supplier_id'] = $supplier_ids[$k];
			}
			if (!empty($prices))
			{
				$data['price'] = $prices[$k];
			}
			//如果是调货
			if (0 == $bound_type_id)
			{
				$stores = explode('|', $store_type[$k]);
				//调货出库
				$data['store_id'] = $stores[0];
				$data['stock_type'] = 'outbound';
				if ( !$this->db->insert($this->TABLE, $data) )
				{
					return $this->error = 'stock_detail_model::create->60:SQL ERROR!';
				}
				$this->Sub_goods_model->update_stock($data['stock_type'], $data['store_id'], $data['sub_goods_id'], $data['quantity']);
				if ( $this->Sub_goods_model->error )
				{
					return $this->error = $this->Sub_goods_model->error;
				}
				//调货入库
				$data['store_id'] = $stores[1];
				$data['stock_type'] = 'inbound';
				if ( !$this->db->insert($this->TABLE, $data) )
				{
					return $this->error = 'stock_detail_model::create->72:SQL ERROR!';
				}
				$this->Sub_goods_model->update_stock($data['stock_type'], $data['store_id'], $data['sub_goods_id'], $data['quantity']);
				if ( $this->Sub_goods_model->error )
				{
					return $this->error = $this->Sub_goods_model->error;
				}
			}
			else
			{
				$data['store_id'] = $store_type[$k];
				//更新stocks_details
				if ( !$this->db->insert($this->TABLE, $data) )
				{
					$this->error = 'stock_detail_model::create->86:SQL ERROR!';
					return;
				}
				//判断出入库、仓位，更新sub_goods
				$this->Sub_goods_model->update_stock($stock_type, $store_type[$k], $data['sub_goods_id'], $data['quantity']);
				if ( $this->Sub_goods_model->error )
				{
					$this->error = $this->Sub_goods_model->error;
					return;
				}
			}
		}
	}

	public function get_detail($stock_id, $get_type='STOCK_ID', $return_type='DETAIL', $regroup=FALSE)
	{
		$this->load->model('Sub_goods_model');
		$this->load->model('Main_goods_model');

		$sub_goods_ids = array();
		$sub_goodies = array();

		if ('STOCK_ID' == $get_type)
		{
			$this->db->where('stock_id', $stock_id);
			$this->db->order_by('sub_goods_id ASC');
		}
		else if ('STOCK_IDS' == $get_type)
		{
			$this->db->where_in('stock_id', $stock_id);
			$this->db->order_by('sub_goods_id ASC');
		}
		else if ('ALL' == $get_type)
		{
			$this->db->order_by('sub_goods_id ASC');
		}
		else
		{
			$this->error = 'ERROR';
			return false;
		}

		if ('DETAIL' == $return_type)
		{
			$query = $this->db->get($this->TABLE)->result();
			foreach ($query as $each)
			{
				if (!in_array($each->sub_goods_id, $sub_goods_ids))
				{
					array_push($sub_goods_ids, $each->sub_goods_id);
				}
			}
			$sub_goodies = $this->Sub_goods_model->get_some($sub_goods_ids);
			
			if ($regroup)
			{
				$rg_query = array();		//存储重组的数据
				$goodies = array();	//存储已经查询出来的主货物
				//遍历子货物获得并组织主货物
				foreach ($sub_goodies as $sub_goods)
				{
					if (isset($goodies['main'][$sub_goods->main_goods_id]))
					{
						$goodies['sub'][$sub_goods->sub_goods_id] = $goodies['main'][$sub_goods->main_goods_id];
					}
					else
					{
						$re_query[$sub_goods->main_goods_id] = array();
						$goodies['main'][$sub_goods->main_goods_id] = $this->Main_goods_model->getOne($sub_goods->main_goods_id);
						$goodies['sub'][$sub_goods->sub_goods_id] = $goodies['main'][$sub_goods->main_goods_id];
					}
				}
				foreach ($query as $key=>$each)
				{
					$rg_query[$goodies['sub'][$each->sub_goods_id]['main_goods_id']]['info'] = $goodies['sub'][$each->sub_goods_id];
					//添加子货品属性
					$each->attribute = $sub_goodies[$each->sub_goods_id]->attribute;
					$rg_query[$goodies['sub'][$each->sub_goods_id]['main_goods_id']]['sub'][] = $each;
				}
				$query = $rg_query;
			}
			else
			{
				foreach ($query as $key=>$each)
				{
					if (in_array($each->sub_goods_id, $sub_goods_ids))
					{
						$query[$key]->sub_goods = $sub_goodies[$each->sub_goods_id];
					}
				}
			}
		}
		else if ('SINGLE' == $return_type)
		{
			$query = $this->db->get($this->TABLE)->result();
		}

		return $query;
	}

	//获得指定类型的库存单
	/***
	public function get_details_by_type($stock_type, $bound_type, $where=array())
	{

		$details = array(); //初始化返回值容器

		try{

			switch ($stock_type) {
				case 'inbound' :
				case 'outbound' :
					$this->db->where('stock_type', $stock_type);
					break;
				
				default:
					$this->error = '需要指定出库或入库 STOCK_TYPE:' . $stock_type;
					return FALSE;
					break;
			}

			$this->db->where('stock_bound_type', $bound_type);
			
			if (!empty($where))
			{
				foreach ($where as $w)
				{
					$this->db->where($w);
				}
			}

			$details = $this->db->get($this->TABLE)->result_array();
			return $details;

		}
		catch(Exception $error)
		{
			$this->error = $error;
			return FALSE;
		}
	}
	***/

	//查询功能
	//销售统计、退货统计等
	public function look_for($type)
	{
		try {
			$start_date = $this->input->post('start_date');
			$end_date = $this->input->post('end_date');

			//根据日期改变日期结构
			$start_date = explode('-', $start_date);
			$end_date = explode('-', $end_date);
			//验证日期格式
			if (!checkdate($start_date[1], $start_date[2], $start_date[0]) || !checkdate($end_date[1], $end_date[2], $end_date[0]))
			{
				$this->error = '请输入有效的日期';
				return FALSE;
			}

			//根据日期改变日期结构:时间戳
			$start_date = mktime(0, 0, 0, $start_date[1], $start_date[2], $start_date[0]);
			$end_date = mktime(0, 0, 0, $end_date[1], $end_date[2], $end_date[0]);
			//验证日期大小
			if ($start_date > $end_date)
			{
				$this->error = '开始日期 不能大于 结束日期';
				return FALSE;
			}

			//根据查询类型过滤数据
			if ('sale' == $type)
			{
				$this->db->where('stock_bound_type', 'sale');
			}
			$this->db->where('create_date >', $start_date);
			$this->db->where('create_date <', $end_date);
			$query = $this->db->get($this->TABLE);

			//初始化新的子货品集
			$sub_goodies = array();
			foreach ($query as $value)
			{
				
			}

		} catch (Exception $e) {
			$this->error = $e;
			return FALSE;
		}
	}

	/*************************
	涉及到结算的方法 开始
	*************************/
	//设置结算标识符
	public function set_balanced($stock_details_id)
	{
		$where = array(
			'stock_details_id'	=> $stock_details_id,
			'balance_flg'		=> ' != 1'
			);
		$this->db->where($where);
		$this->db->limit(1);
		$query = $this->db->get($this->TABLE);
		if (1 == $query->num_rows())
		{
			$where = array(
				'stock_details_id'	=> $stock_details_id
				);
			$set = array(
				'balance_flg'	=> 1
				);
			$this->db->set($set);
			$this->db->where($where);
			$this->db->limit(1);
			if ($this->db->update($this->TABLE))
			{
				return TRUE;
			}
			else
			{
				$this->error = 'CANNOT_SET_BALANCED';
			}
		}
		else
		{
			$this->error = 'BALANCED';
		}
		return FALSE;

	}

	//关联结算报表
	public function relate_advice($stock_detail_id, $advice_id)
	{
		$where = array(
			'stock_details_id'	=> $stock_detail_id
			);
		$set = array(
			'advice_id'	=> $advice_id
			);
		$this->db->set($set)->where($where)->limit(1);
		if ($this->db->update($this->TABLE))
		{
			if (1 == $this->db->affected_rows())
			{
				return TRUE;
			}
			else
			{
				$this->error = 'CANNOT_RELATE_ADVICE';
			}
		}
		else
		{
			echo $this->db->last_query();
			$this->error = 'CANNOT_RELATE_ADVICE';
		}
		return FALSE;
	}

	public function set_balance_price($stock_details_id, $price)
	{
		$where = array('stock_details_id'=>$stock_details_id);
		$set = array('price'=>$price);
		if ($query = $this->db->set($set)->where($where)->update($this->TABLE))
		{
			return TRUE;
		}
		else
		{
			$this->error = '更新库存单价格出错';
		}
		return FALSE;
	}

	/*************************
	涉及到结算的方法 结束
	*************************/

	//自定义查询方法
	public function custom_query($type=FALSE, $where=FALSE, $data=FALSE)
	{
		switch ($type) {
			case 'get':
				if ($where)
				{
					$this->db->where($where);
				}
				if ($query = $this->db->get($this->TABLE))
				{
					return $query->result();
				}
				else
				{
					$this->error = 'QUERY_FAILED';
					return FALSE;
				}
				break;

			case 'update':
				if ($where)
				{
					$this->db->where($where);
				}
				else
				{
					$this->error = 'NOT_SET_WHERE';
					return FALSE;
				}
				if ($this->db->update($this->TABLE, $data))
				{
					return TRUE;
				}
				else
				{
					$this->error = 'QUERY_FAILED';
					return FALSE;
				}

			default:
				$this->error = 'NOT_SET_QUERY_TYPE';
				return FALSE;
			break;
		}
	}

}